package com.yunhuakeji.wddx.utils;

import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class HttpPostTool {
	
	@SuppressWarnings({ "deprecation" })
	public static String post(String url, String[] paramsName,String[] paramsValue) {
		if (paramsName!=null&&paramsValue!=null&&paramsName.length != paramsValue.length) {
				return "";
		} else {
			HttpEntity entity = null;
				HttpClient hc = new DefaultHttpClient();
				HttpPost httpPost = new HttpPost(url);
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				if(paramsName!=null||paramsValue!=null)
				{
					for (int i = 0; i < paramsName.length; i++) 
					{
						nvps.add(new BasicNameValuePair(paramsName[i],
								paramsValue[i]));
					}
				}
				HttpResponse response = null;
				try {
					httpPost.setEntity(new UrlEncodedFormEntity(nvps,
							HTTP.UTF_8));
					response = hc.execute(httpPost);
				} catch (ClientProtocolException e) 
				{
					e.printStackTrace();
				} catch (IOException e) 
				{
					e.printStackTrace();
				}
				entity = response.getEntity();
				InputStream instreams = null;
				try {
					instreams = entity.getContent();
	
				} catch (IllegalStateException e) 
				{	
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				String str = convertStreamToString(instreams);
 				return str;
			} 				
		}

	public static String convertStreamToString(InputStream is) 
	{
		BufferedReader reader;
		try {
			reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
			StringBuilder sb = new StringBuilder();
			String line = null;
		try {
			while ((line = reader.readLine()) != null) 
			{
				sb.append(line + "\n");
			}
		} catch (IOException e) 
		{
			e.printStackTrace();
		} finally 
		{
			try 
			{
				is.close();
			} catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
		return sb.toString();
		} catch (UnsupportedEncodingException e1) 
		{
			return "";
		}
	}
}
